package info.pablo.com;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class SignIn
 */
@WebServlet("/SignIn")
public class SignIn extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SignIn() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		
		//PrintWriter output = response.getWriter();
		//String login = request.getParameter("login");
		//String password = request.getParameter("password");
		
		
		this.getServletContext().getRequestDispatcher("/Private.jsp").
		forward(request, response);	
		return;
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		
		PrintWriter output = response.getWriter();
		String login = request.getParameter("login");
		String password = request.getParameter("password");
		

		Pattern pattern = Pattern.compile("^[a-z0-9A-Z]{5,}$");//esto lo que hace es : de principio a fin 8 caracteres
		Matcher loginChecker = pattern.matcher(login);
		Matcher passwordChecker = pattern.matcher(password);
		boolean anyErrors = false;
		
		if(!loginChecker.find()){
			request.setAttribute("loginerror", "login");
			anyErrors = true;
		}
		
		if(!passwordChecker.find()){
			request.setAttribute("paswordError", "password");
			anyErrors = true;
		}
		if (anyErrors){
			this.getServletContext().
			getRequestDispatcher("/login.jsp").
				forward(request, response);
			return;
		}
		
		if(login.equals("falken") && password.equals("josua")){
			
			session.setAttribute("login", login);
			this.getServletContext().
				getRequestDispatcher("/Private.jsp").
					forward(request, response);
			System.out.println("Login correct");
			
		}else{
			this.getServletContext().getRequestDispatcher("/login.jsp").
				forward(request, response);	
			System.out.println("Login incorrect");
			return;
		}
				
	}

}
